package dao;

import model.Level;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

import java.util.List;

/**
 * Created by VLAD on 07.07.2014.
 */
public class LevelDao implements ILevelDao {

    @Override
    public int saveLevel(Level level)
    {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = null;
        Integer levelID = null;
        tx = session.beginTransaction();
        levelID = (Integer)session.save(level);
        tx.commit();
        return levelID;

    }

    @Override
    public Level getLevelByID(int id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = null;
        Integer levelID = null;
        Level level = null;
        try
        {
            tx = session.beginTransaction();
            level = (Level)session.get(Level.class, id);
            tx.commit();
        } catch (Exception ex){

        }

        return level;
    }

    @Override
    public Level getLevelByPoints(long points)
    {
        if(points != 0) {
            String query = "FROM model.Level L WHERE L.points <= " + points + " ORDER BY L.id DESC";
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction tx = null;
            tx = session.beginTransaction();
            Level level = (Level) session.createQuery(query).list().get(0);
            tx.commit();
            return level;
        }
        else {
            return getLevelByID(1);
        }

    }
}
